package com.example.jackson.csv;

import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.databind.SequenceWriter;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;

import java.io.File;
import java.io.IOException;

public class CsvDatabase<T> {
    private final CsvMapper mapper = CsvMapper.csvBuilder().build();

    private final File file;
    private final Class<T> clazz;
    private final CsvSchema schema;

    public CsvDatabase(String path, Class<T> clazz) {
        this.file = new File(path);
        this.clazz = clazz;
        this.schema = mapper.schemaFor(clazz).withHeader();
    }

    public void add(T row) throws IOException {
        T fileRow = this.find(row);
        if (fileRow != null) {
            return;
        }
        try (SequenceWriter writer = writer()) {
            writer.write(row);
            writer.flush();
        }
    }

    public T find(T row) throws IOException {
        try (MappingIterator<T> mappingIterator = reader()) {
            while (mappingIterator.hasNext()) {
                T fileRow = mappingIterator.next();
                if (this.assertEquals(fileRow, row)) {
                    return fileRow;
                }
            }
        }
        return null;
    }

    public void delete(T row) {

    }

    protected boolean assertEquals(T fileRow, T currentRow) {
        return false;
    }

    private MappingIterator<T> reader() throws IOException {
        return mapper.readerFor(clazz).with(schema).readValues(file);
    }

    private SequenceWriter writer() throws IOException {
        return mapper.writerFor(clazz).with(schema).writeValues(file);
    }
}
